
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 部署client jar
 */
public class DeployEntry {

    private final Path FROM_WEBINF_LIB;
    private final Path FROM_WEBINF_CLASSES;
    private final Path TO_WEBINF_EXTEND;

    private final Path TO_EXTERNAL_LIB;
    private final Path TO_EXTERNAL_CLASSES;


    public DeployEntry(String FIELD_NC_HOME) {
        FROM_WEBINF_LIB = Paths.get(FIELD_NC_HOME, "hotwebs/nccloud/WEB-INF/lib");
        FROM_WEBINF_CLASSES = Paths.get(FIELD_NC_HOME, "hotwebs/nccloud/WEB-INF/classes");
        TO_WEBINF_EXTEND = Paths.get(FIELD_NC_HOME, "hotwebs/nccloud/WEB-INF/extend/");

        TO_EXTERNAL_LIB = Paths.get(FIELD_NC_HOME, "external/lib");
        TO_EXTERNAL_CLASSES = Paths.get(FIELD_NC_HOME, "external/classes");
    }


	public static void run(String home) throws IOException {
		new DeployEntry(home.strip()).run();
	}


    public void run() throws IOException {
        copyConfig();
        moveJar();
        moveClasses();
    }

    private void copyConfig() throws IOException {
        File[] fromFiles = FROM_WEBINF_LIB.toFile().listFiles();
        for (File fromFile : fromFiles) {
            if (fromFile.getName().endsWith(".jar")) {
                System.out.println(fromFile.getName());
                _doCopy(fromFile);
            }
        }

        System.out.println(">>> move hotwebs/nccloud/WEB-INF/extend/yyconfig/** success");
    }

    private void _doCopy(File fromFile) throws IOException {
        try (JarFile jarFile = new JarFile(fromFile);) {
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry jarEntry = entries.nextElement();
                String fileName = jarEntry.getName();
                if (fileName.startsWith("yyconfig")) {
                    if (fileName.endsWith(".xml") || fileName.endsWith(".json")) {
                        // ensure parent directory exists
                        Path targetFilename = TO_WEBINF_EXTEND.resolve(fileName);
                        targetFilename.getParent().toFile().mkdirs();
                        // copy filename
                        InputStream input = jarFile.getInputStream(jarEntry);
                        Files.copy(input, targetFilename, StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            }
        }
    }

    private void moveJar() throws IOException {
        File[] fromFiles = FROM_WEBINF_LIB.toFile().listFiles();
        for (File fromFile : fromFiles) {
            if (fromFile.getName().endsWith(".jar")) {
                System.out.println(fromFile.getName());
                // ensure file not exists
                Path targetFilename = TO_EXTERNAL_LIB.resolve(fromFile.getName());
                if (targetFilename.toFile().exists()) {
                    targetFilename.toFile().delete();
                }
                // copy file
                Files.move(fromFile.toPath(), targetFilename, StandardCopyOption.REPLACE_EXISTING);
            }
        }

        System.out.println(">>> move hotwebs/nccloud/WEB-INF/lib/** success");
    }

    private void moveClasses() throws IOException {
        String glob = "glob:**/*.{java,txt,class,xml}";
        final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);
        Files.walkFileTree(FROM_WEBINF_CLASSES, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path source, BasicFileAttributes attrs) throws IOException {
                if (pathMatcher.matches(source)) {
                    System.out.println(source);
                    Path relativize = FROM_WEBINF_CLASSES.relativize(source);
                    System.out.println(relativize.getFileName());

                    Path target = TO_EXTERNAL_CLASSES.resolve(relativize);
                    target.getParent().toFile().mkdirs();
                    Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
                }
                return FileVisitResult.CONTINUE;
            }


            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        });

        System.out.println(">>> move hotwebs/nccloud/WEB-INF/classes/** success");
    }


}
